package cn.seqdata.cxf.interceptor;

import java.io.InputStream;
import java.io.Reader;

import javax.ws.rs.core.Response;

import org.apache.cxf.interceptor.AbstractOutDatabindingInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.message.MessageContentsList;
import org.apache.cxf.phase.Phase;

import cn.seqdata.cxf.wrapper.WrapperBean;
import cn.seqdata.cxf.wrapper.WrapperContent;

public class WrappedOutInterceptor extends AbstractOutDatabindingInterceptor {

	public WrappedOutInterceptor() {
		super(Phase.MARSHAL);
	}

	@Override
	public void handleMessage(Message message) throws Fault {
		MessageContentsList objs = MessageContentsList.getContentsList(message);
		if (objs == null || objs.size() == 0) {
			return;
		}

		Object responseObj = objs.get(0);

		// 没有返回值的函数，responseObj=null
		if (null == responseObj) {
			return;
		}

		// Response一般是定制输出，不做包装
		if (responseObj instanceof Response) {
			return;
		}

		// 流，直接转换为输出
		if (responseObj instanceof InputStream || responseObj instanceof Reader) {
			return;
		}

		// 已经包装过的，不再包装
		if (responseObj instanceof WrapperBean) {
			return;
		}

		// 包装后替换掉原来的对象
		WrapperBean wrapper = new WrapperContent(responseObj);
		objs.set(0, wrapper);
	}
}
